package com.snow.campuslink.aspects;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.amqp.core.Message;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * TODO
 *
 * @author Gaosl
 * @className RabbitListenerAspect
 * @date 2021/3/24 13:54
 */
@Component
@Aspect
@Slf4j
public class RabbitListenerAspect {
    /**
     * 切点
     */
    @Pointcut("@annotation(org.springframework.amqp.rabbit.annotation.RabbitListener)")
    public void rabbitListenerPointCut() {
    }

    @Around("rabbitListenerPointCut()")
    public Object doAround(ProceedingJoinPoint point) throws Throwable {
        Object[] args = point.getArgs();
        Channel channel = (Channel) args[0];
        Message message = (Message) args[1];
        String queue = message.getMessageProperties().getConsumerQueue();
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        String body = new String(message.getBody(), StandardCharsets.UTF_8);
        log.info("队列:{},获取到MQ推送:{}", queue, body);
        Object result = null;
        try {
            result = point.proceed(args);
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            log.error("队列:"+queue+"消息消费失败，body:"+body,e);
            channel.basicAck(deliveryTag, false);
        }
        return result;
    }


}
